package tcp.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class Client {
	private String host = "127.0.0.1";
	private int port = 9999;
	private Socket socket;
	
	public Client() throws IOException{
		//socket = new Socket(host,port);
		//如果要限制建立连接的时间，需要使用无参构造
		socket = new Socket();
		socket.bind(new InetSocketAddress("127.0.0.1",15241));
			SocketAddress address = new InetSocketAddress(host, port);
		socket.connect(address, 2000);
	}
	
	/**
	 * @param host
	 * @param port
	 * @throws IOException
	 */
	public Client(String host,int port) throws IOException{
		this.host = host;
		this.port = port;
		socket = new Socket(host,port);
	}
	
	private PrintWriter getWriter(Socket socket) throws IOException{
		OutputStream os = socket.getOutputStream();
		return new PrintWriter(os);
	}
	
	private BufferedReader getReader(Socket socket) throws IOException{
		InputStream is = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(is));
	}
	
	public void talk(){
		try {
			final BufferedReader br = getReader(socket);
			new Thread(){
				public void run() {
					while(true){
						try {
							System.out.println(br.readLine());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};
			}.start();
			PrintWriter pw = getWriter(socket);
			BufferedReader msgReader = new BufferedReader(new InputStreamReader(System.in));
			String msg = null;
			while((msg = msgReader.readLine()) != null){
				pw.println(msg);
				pw.flush();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) throws IOException {
		//测试支持连接数
//		for(int i =0 ;i<100;i++){
//			Client client = new Client();
//			System.out.println(i);
//		}
		Client client = new Client();
		client.talk();
	}
}
